package com.esd.bs.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.esd.collection.DbFile;
import com.esd.collection.History;
import com.esd.common.MongoDBUtil;
import com.esd.core.WebclientFormSubmit;
import com.esd.dao.MongoDBDao;
import com.esd.entity.SearchHtml;
import com.esd.entity.SearchResult;

@Controller
public class NanChangSearchController {
	@Resource
	private MongoDBUtil mdu;
	@Resource
	private MongoDBDao mongoDBDao;
	/**
	 * 南昌查询页点击查询
	 * cc 20171025
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "nanchangSearch", method = RequestMethod.GET)
	public ModelAndView nanchangSearch(HttpServletRequest request,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		String keyWord = null;
		int currentPage = 0;
		try {
			keyWord = URLDecoder.decode(request.getParameter("keyWord"), "UTF-8");
			currentPage = Integer.valueOf(request.getParameter("currentPage")) ;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("keyWord", keyWord);

		String siteId = session.getAttribute("siteId").toString();
		Criteria criatira = new Criteria();
		criatira.andOperator(Criteria.where("title").regex(keyWord));
		List<DbFile> list = mdu.findFiles(new Query(criatira).skip((currentPage - 1)*15).limit(15),siteId+"_html");
//		List<DbFile> list1 = new ArrayList<DbFile>();
//		for (int i = (currentPage-1)*15 ; i < currentPage*15; i++) {
//			list1.add(list.get(i));
//		}
		map.put("list", list);
		long total = mongoDBDao.countByCollectionName(new Query(criatira), DbFile.class,siteId+"_html");
		SearchHtml searchHtml = new SearchHtml();
		searchHtml.setHtml(list);
		searchHtml.setCurrentPage(currentPage);
		searchHtml.setSerCon(keyWord);
		searchHtml.setTotal(total);
		searchHtml.setTotalPage(total % 15 == 0 ? (int) total / 15 : (int) (total / 15) + 1);
		map.put("html", searchHtml);
		
//		WebclientFormSubmit wfs = new WebclientFormSubmit();
//		map = wfs.nanchangSearch(keyWord);
		return new ModelAndView("nanchangSearch",map);
	}
}
